$(document).ready(function() {

	var PAGE_SIZE = 25;

	var busy_count = 0;
	function beginAjax() {
		if(busy_count == 0) {
			$('#search-results').addClass('busy');
		}		
		busy_count++;
	}
	
	function endAjax() {
		busy_count--;
		if(busy_count == 0) {
			$('#search-results').removeClass('busy');
		}
	}
	
	$(window).bind('hashchange', function() {
		var search = $.bbq.getState('q');
		var kind = $.bbq.getState('kind');
		var offset = $.bbq.getState('offset');
		
		$('#search-text').val(search);
		$('#search-kind').val(kind);
		
		fetchDataFromServer(search, kind, offset);
	});

	$(window).trigger('hashchange');

	$('#search-text').typeWatch({
		captureLength: 0,
		callback: function() {
			var $debug = $('#debug');			
			fetchData($('#search-text').val(), getLibraryKind(), 0);
		}
	});
	
	$('#library-kind').change(function() {
		fetchData($('#search-text').val(), getLibraryKind(), 0);
	});

	function getLibraryKind() {
		return $('#library-kind').val();
	}
	
	function fetchData(search, kind, offset) {
		var state = { q : search || '' };
		if(kind) {
			state.kind = kind;
		}
		
		if(offset > 0) {
			state.offset = offset;
		}

		$.bbq.pushState(state, 2);
	}
	
	function fetchDataFromServer(search, kind, offset) {
	
		var url = '/library/search';

		beginAjax();
		jQuery.ajax({

			url: url,
			
			data: {
				q: search,
				offset: offset,
				kind: kind,
				limit: PAGE_SIZE
			},

			success: function(data, textStatus, jqXHR) {
				updateTable($.parseJSON(jqXHR.responseText));
				endAjax();
			},

			error: function(jqXHR, textStatus, errorThrown) {
				endAjax();
			}
		});
	}
	
	function updateTable(results) {
		var libs = results.items;
		var $title = $('#search-results thead tr th');

		var info = '';
		if(results.query) {
			info = "'" + results.query + "'";
		}		
		info += " [" + (results.offset + 1) + " - " + (results.offset + libs.length) + " of " + results.count + "]";
		$('title').text('BookBurrito Library Database: ' + info);
		$title.text("Search Results: " + info);

		var $pager = buildPager(results, function(results, offset, title) {
			return $('<a href="#"/>')
				.html(title)
				.attr('title', (offset + 1) + "...")
				.data('offset', offset)
				.click(function() {
					fetchData(results.query, results.kind, offset);
					return false;
				});
		}, PAGE_SIZE);
		
		$title.append($pager);

		var $tbody = $('#search-results tbody');
		$tbody.empty();
		for(var i = 0; i < libs.length; i++) {
			var lib = libs[i];
			var $tr = $('<tr/>').append(
				$('<td/>').html(
					$('<a>').text(lib.title).attr('href', lib.link.replace('#{ISBN}', lib.have))
				).attr('class', lib.is_community ? 'community' : 'validated')
			);
			$tbody.append($tr);
		}
	}
});